﻿using DataAccess;
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
namespace DataProcess
{
    public partial class frmCHM : Form
    {
        private string textPath = @"D:\Projects\数据处理或导出\中药材\提交给软件部\专论文章";
        private string dbPath = @"D:\Projects\中药材.accdb";
        public frmCHM()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder();
            builder.DataSource = dbPath;
            builder.Provider = "Microsoft.ACE.OLEDB.12.0";
            Article.Db = new DataAccess.Database("chm", "System.Data.OleDb", builder.ConnectionString);

            string[] files = Directory.GetFiles(textPath, "*.txt");
            List<string> tags = new List<string>();
            foreach (string file in files)
            {
                var article = new Article(file);
                article.SaveToDatabase();
            }
            var checkChmid = (int)Article.Db.ExecuteScalar("SELECT COUNT(*) FROM chm_images WHERE chmid IS NULL");
            if (checkChmid > 0)
            {
                Article.Db.ExecuteNonQuery("UPDATE chm_images INNER JOIN chm_main ON chm_images.文章名称 = chm_main.chm_title SET chm_images.chmid = [chm_main].[chmid] WHERE chm_images.chmid Is Null");
            }

            var data = Article.Db.ExecuteDataTable("SELECT chm_imageid,chmid,imagestream FROM chm_images WHERE Not chmid Is Null AND Not imagename Is Null ORDER BY chmid,chm_imageid");
            int lastimageid = 0;
            int index = 0;
            for (int i = 0; i < data.Rows.Count; i++)
            {
                int currentImageid = Convert.ToInt32(data.Rows[i]["chmid"]);
                if (currentImageid != lastimageid)
                {
                    lastimageid = currentImageid;
                    index = 0;
                }
                string ext = GetImageFormat((byte[])data.Rows[i]["imagestream"]).Split('.')[1];
                Article.Db.ExecuteNonQuery("UPDATE chm_images SET filename = @filename WHERE chm_imageid=@chm_imageid", new Parameter("filename", string.Format("{0}_{1}.{2}", lastimageid, (++index).ToString().PadLeft(3, '0'), ext)), new Parameter("chm_imageid", data.Rows[i]["chm_imageid"]));
            }
            MessageBox.Show("导入Access完成！", "完成");
        }
        public string GetImageFormat(byte[] data)
        {
            Image img = Image.FromStream(new MemoryStream(data));

            var codeinfo = ImageCodecInfo.GetImageEncoders();
            for (int i = 0; i < codeinfo.Length; i++)
            {
                if (codeinfo[i].FormatID.Equals(img.RawFormat.Guid))
                {
                    return codeinfo[i].FilenameExtension.Split(';')[0];
                }
            }
            return string.Empty;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder();
            builder.DataSource = dbPath;
            builder.Provider = "Microsoft.ACE.OLEDB.12.0";
            Article.Db = new DataAccess.Database("chm", "System.Data.OleDb", builder.ConnectionString);

            string[] files = Directory.GetFiles(textPath, "*.txt");
            List<string> tags = new List<string>();
            foreach (string file in files)
            {
                var article = new Article(file);
                article.SaveToDatabase(getNames: false);
            }

            MessageBox.Show("导入Access完成！", "完成");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string dbPath = @"D:\Projects\数据处理或导出\中药材\图片表.accdb";
            string outPath = @"D:\Projects\数据处理或导出\中药材\images";
            OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder();
            builder.DataSource = dbPath;
            builder.Provider = "Microsoft.ACE.OLEDB.12.0";
            var db = new DataAccess.Database("chm", "System.Data.OleDb", builder.ConnectionString);
            using (var reader = db.ExecuteReader("SELECT * FROM [chm_images 2016]"))
            {
                while (reader.Read())
                {
                    File.WriteAllBytes(Path.Combine(outPath, reader["imagename"].ToString() + ".jpg"), (byte[])reader["imagestream"]);
                }
            }
        }
    }
}
